<%@ page language="java" import="java.lang.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
	String path = request.getContextPath();
%>
<style>
	.floatLR{
		float: left;
		margin-right: 10px;
	}
</style>
<div class="row-fluid" style="height: inherit;margin:0px;border: 0px">
	<div id="condition_search" style="margin:10px;">
		<label class="inline" >EBS盘点单号：</label>
		<input type="text" style="width:150px;margin-right:10px;" value="${ebsCode}" readonly="readonly"/>
		<span style="width:50px;margin-left: 10px;">质保号：</span>
		<input id="qacode" name="qacode" type="text" style="width: calc(20% - 5px);" placeholder="质保单号" >
		<span  style="width:50px;margin-left: 10px;">盘点结果：</span>
		<input id="inventoryReview_list_inventoryResult" name="inventoryResult" type="text" style="width: calc(15% - 85px);" placeholder="盘点结果">
		<div class="btn btn-info" onclick="queryByParam();">
			<i class="ace-icon fa fa-check bigger-110"></i>查询
		</div>
		<div class="btn" onclick="inventoryReview_edit_reset();"><i class="ace-icon icon-remove"></i>重置</div>
		<input type="text" class="date-picker" id="inventoryReview_edit_time" name="time" style="width: calc(14% - 40px);margin-left: 20px;" value="${auditTime}"
			   placeholder="请选择盘库截止日期" />
		<button id="inventoryReview_edit_timeConfirm" class="btn btn-xs btn-primary btn-info" >
			<i class="" style="margin-right:6px;"></i>更新审核日期
		</button>
		<%--<button id="inventoryReview_edit_allMoveBtn" class="btn btn-xs btn-primary btn-info" >
			<i class="" style="margin-right:6px;"></i>库位审核
		</button>--%>
		<button id="inventoryReview_edit_addMaterialBtn" class="btn btn-xs btn-primary btn-info" style="margin-left: 100px;">
			<i class="" style="margin-right:6px;"></i>全部审核
		</button>
	</div>
	<!-- 表格div -->
	<div id="inventoryReview_edit_grid-div-c" style="width:100%;margin:10px auto;">
		<!-- 表格工具栏 -->
		<div id="inventoryReview_edit_fixed_tool_div" class="fixed_tool_div detailToolBar">
			<div id="inventoryReview_edit_toolbar_-c" style="float:left;overflow:hidden;"></div>
		</div>
		<!-- 信息表格 -->
		<table id="inventoryReview_edit_grid-table-c" style="width:100%;height:100%;"></table>
		<!-- 表格分页栏 -->
		<div id="inventoryReview_edit_grid-pager-c"></div>
	</div>
</div>
<div id="inventoryReview_edit_doing"></div>
<script type="text/javascript">
	var inventoryReview_edit_dynamicDefalutValue="cbe154ed57f14f8e09803c4d0982a4d17c";
	//ajax请求状态：0不能请求，1可以请求
	var ajaxStatus = 1, ajaxStatusMoveBtn = 1;
	//ebs盘点单号（去杠去英文）
	var id = '${id}';
	//ebs盘点单号（real）
	var ebs_code = '${ebsCode}';
    var context_path = '<%=path%>';
	//wms盘点单号
    var code = '${code}';
	//表格对象
    var _grid_detail;

	//时间控件
	$(".date-picker").datetimepicker({
		format: "YYYY-MM-DD HH:mm:ss" ,
		autoclose : true,
		todayHighlight : true
	});

	var stringToDate = function(dateStr,separator){
		if(!separator){
			separator="-";
		}
		var dateArr = dateStr.split(separator);
		var year = parseInt(dateArr[0]);
		var month;
		//处理月份为04这样的情况
		if(dateArr[1].indexOf("0") == 0){
			month = parseInt(dateArr[1].substring(1));
		}else{
			month = parseInt(dateArr[1]);
		}
		var day = parseInt(dateArr[2]);
		var date = new Date(year,month -1,day);
		return date;
	};

	_grid_detail = jQuery("#inventoryReview_edit_grid-table-c").jqGrid({
        url : context_path + "/inventoryRegistration/resultList.do?wmsCode="+code,
        datatype : "json",
		colNames : [ "操作","盘点结果","审核库位状态","审核米数状态","质保单号","批次号","库存数量","盘点数量","库存库位","盘点库位","盘点人","盘点时间","入库时间","盘号",
			"物料编码"],
		colModel : [
			{name : "cz",index : "ys.id",width :90, formatter:function(cellValu,option,rowObject){
					let qaCode = '"'+rowObject.qaCode+'"';
					let isShow = rowObject.state == '1' && (rowObject.shelfState == 1 || rowObject.shelfState == 2);
					return "<button id='b1'+rowObject.id class='btn btn-info floatLR' "+(isShow ? 'disabled' : '')+" onclick='shPassSolo("+qaCode+")'>审核</button>"
							/*+ "<button id='b2'+rowObject.id class='btn btn-info floatR' onclick='ykPassSolo("+qaCode+")'>移库</button>"*/;
				}
			},
			{name : "result",index:"yr.result,ys.id",width : 90,
				formatter:function(cellValu,option,rowObject){
					if(cellValu=='1'){
						return "<span style='color:rosybrown;font-weight:bold;'>正常</span>";
					}else if(cellValu=='2'){
						return "<span style='color:red;font-weight:bold;'>盘盈</span>";
					}else if(cellValu=='3'){
						return "<span style='color:green;font-weight:bold;'>盘亏</span>";
					}else if(cellValu=='4'){
						return "<span style='color:darkslategray;font-weight:bold;'>错位正常</span>";
					}else if(cellValu=='5'){
						return "<span style='color:mediumvioletred;font-weight:bold;'>错位盘盈</span>";
					}else if(cellValu=='6'){
						return "<span style='color:darkgreen;font-weight:bold;'>错位盘亏</span>";
					}else {
						if (new Date($("#inventoryReview_edit_time").val()) < new Date(rowObject.inStorageTime)){
							return "<span style='color:goldenrod;font-weight:bold;'>新入库</span>";
						} else {
							return "<span style='color:black;font-weight:bold;'>漏盘</span>";
						}
					}
				}
			 },
			{name : "shelfState",index:"yr.shelf_state,ys.id",width : 90,
				formatter:function(cellValu,option,rowObject){
					if(cellValu==0){
						return "<span style='color:red;font-weight:bold;'>移库失败</span>";
					}else if(cellValu==1){
						return "<span style='color:green;font-weight:bold;'>移库成功</span>";
					}else if(cellValu==2){
						return "<span style='color:green;font-weight:bold;'>无需移库</span>";
					}else if (cellValu==3) {
						return "<span style='color:blue;font-weight:bold;'>移库待执行</span>";
					}else {
						return "<span style='color:darkcyan;font-weight:bold;'>未盘点</span>";
					}
				}
			},
			{name : "state",index:"yr.state",width : 90,
				formatter:function(cellValu,option,rowObject){
					if(cellValu==0){
						return "<span style='color:red;font-weight:bold;'>同步数量失败</span>";
					}else if(cellValu==1){
						return "<span style='color:green;font-weight:bold;'>同步数量成功</span>";
					}else if (cellValu==3) {
						return "<span style='color:blue;font-weight:bold;'>同步数量待执行</span>";
					}else {
						return "<span style='color:darkcyan;font-weight:bold;'>未盘点</span>";
					}
				}
			},
			{name : "qaCode",index:"ys.qacode",width : 165},
			{name : "batchNo",index:"ys.batch_no",width : 165},
			{name : "meter",index:"ys.meter",width : 113},
			{name : "inventoryMeter",index:"yr.editmeter",width : 113,
				editable : true,
				editrules: {custom: true, custom_func: numberRegex},
				editoptions: {
					size: 25,
					dataEvents: [
						{
							type: 'blur',     //blur,focus,change.............
							fn: function (e) {
								var $element = e.currentTarget;
								var $elementId = $element.id;
								var rowid = $elementId.split("_")[0];
								var qaCode = $element.parentElement.parentElement.children[5].textContent;
								var reg = new RegExp("([1-9][0-9]*(\\.\\d{1,2})?)|(0\\.\\d{1,2})");
								if (!reg.test($("#"+$elementId).val())) {
									layer.alert("非法的数量！(注：请输入正数)");
									return;
								}
								$.ajax({
									url:context_path + '/inventoryReview/updateAmount',
									type:"POST",
									data:{
										qaCode : qaCode,
										amount : $("#"+rowid+"_inventoryMeter").val(),
										ebsCode : ebs_code
									},
									dataType:"json",
									success:function(data){
										if (data.result){
											layer.msg(data.msg,{icon:1});
										} else {
											layer.msg(data.msg,{icon:4});
										}

										$("#inventoryReview_edit_grid-table-c").jqGrid('setGridParam', {
											url : context_path + '/inventoryRegistration/resultList.do?wmsCode=' + code,
											postData: {queryJsonString : $("#qacode").val()} //发送数据  :选中的节点
										}).trigger("reloadGrid");
									}
								});
							}
						}
					]
				}
			},
			{name : "shelfCode",index:"ys.shelfcode",width : 120},
			{name : "inventoryShelf",index:"yr.editshelf",width : 120,
				editable : true,
				editrules: {custom: true},
				editoptions: {
					size: 25,
					dataEvents: [
						{
							type: 'blur',     //blur,focus,change.............
							fn: function (e) {
								var $element = e.currentTarget;
								var $elementId = $element.id;
								var rowid = $elementId.split("_")[0];
								var qaCode = $element.parentElement.parentElement.children[5].textContent;
								$.ajax({
									url:context_path + '/inventoryReview/updateShelf',
									type:"POST",
									data:{
										qaCode : qaCode,
										shelfCode : $("#"+rowid+"_inventoryShelf").val(),
										ebsCode : ebs_code
									},
									dataType:"json",
									success:function(data){
										if (data.result){
											layer.msg(data.msg,{icon:1});
										} else {
											layer.msg(data.msg,{icon:4});
										}

										$("#inventoryReview_edit_grid-table-c").jqGrid('setGridParam', {
											url : context_path + '/inventoryRegistration/resultList.do?wmsCode='+code,
											postData: {queryJsonString : $("#qacode").val()} //发送数据  :选中的节点
										}).trigger("reloadGrid");
									}
								});
							}
						}
					]
				}
			},
			{name : "inventoryName",index:"yr.user_code",width : 110},
			{name : "uploadTime",index:"yr.UPLOAD_TIME",width : 140},
			{name : "inStorageTime",index:"ys.inStorageTime",width : 140},
			{name : "dishcode",index : "yd.dishcode",width : 165},
			{name : "materialCode",index : "yd.materialcode",width : 120}
		],
        rowNum : 20,
        rowList : [ 10, 20, 30 ],
        pager : "#inventoryReview_edit_grid-pager-c",
        sortname : "ys.id",
        sortorder : "asc",
        altRows: true,
        viewrecords : true,
        caption : "详情列表",
        autowidth:true,
        multiselect:true,
        multiboxonly: true,
		shrinkToFit:false,
		autoScroll: true,
		beforeRequest:function (){
			dynamicGetColumns(inventoryReview_edit_dynamicDefalutValue,"inventoryReview_edit_grid-table-c",$(window).width()-$("#sidebar").width() -7);
			//重新加载列属性
		},
        loadComplete : function(data){
            var table = this;
            setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
			$("#inventoryReview_edit_grid-table-c").closest(".ui-jqgrid-bdiv").css({ 'overflow-x': 'auto' });
        },
		cellEdit: true,
		cellsubmit : "clientArray",
        emptyrecords: "没有相关记录",
        loadtext: "加载中...",
        pgtext : "页码 {0} / {1}页",
        recordtext: "显示 {0} - {1}共{2}条数据",
    });

    //在分页工具栏中添加按钮
    $("#inventoryReview_edit_grid-table-c").navGrid("#inventoryReview_edit_grid-pager-c", {edit:false,add:false,del:false,search:false,refresh:false})
	.navButtonAdd("#inventoryReview_edit_grid-pager-c",{
        caption:"",
        buttonicon:"ace-icon fa fa-refresh green",
        onClickButton: function(){
			$("#inventoryReview_edit_grid-table-c").jqGrid("setGridParam", {
				postData: {queryJsonString:""} //发送数据
			}).trigger("reloadGrid");
		}
    });

    $(window).on("resize.jqGrid", function () {
        $("#inventoryReview_edit_grid-table-c").jqGrid("setGridWidth", $("#inventoryReview_edit_grid-div-c").width() - 3 );
        $("#inventoryReview_edit_grid-table-c").jqGrid("setGridHeight", (document.documentElement.clientHeight - $("#inventoryReview_edit_grid-pager-c").height() - 380) );
    });

    $(window).triggerHandler("resize.jqGrid");

	function compareTime(startTime,stopTime){
		var intStartTime=0;
		if(typeof startTime=='string' && startTime.constructor==String ){
			var  startTimeArray=startTime.split(":");
			if(startTimeArray.length ==3){
				intStartTime= startTimeArray[0].replaceAll(" ","").replaceAll("-","") *3600+startTimeArray[1] *60+startTimeArray[2];
			}else{
				$.jBox.info("开始时间格式错误");
				return false;
			}
		}else{
			$.jBox.info("开始时间格式错误");
			return false;
		}

		var intStopTime =0;
		if(typeof stopTime=='string' && stopTime.constructor==String ){
			var  stopTimeArray=stopTime.split(":");
			if(stopTimeArray.length ==3){
				intStopTime =stopTimeArray[0] *3600+stopTimeArray[1] *60+stopTimeArray[2];
			}else{
				$.jBox.info("结束时间格式错误");
				return false;
			}

		}else{
			$.jBox.info("结束时间格式错误");
			return false;
		}

		if(intStopTime<intStartTime){
			return false;
		}
	}

    function ObjData(key,value){
    	this.Key=key;
    	this.Value=value;
    }

    //单个审核
	function shPassSolo(qaCode){
		if(ajaxStatus==0){
			layer.msg("操作进行中，请稍后...",{icon:2});
			return;
		}

		layer.confirm("确定审核通过吗？",function(){
			if(ajaxStatus==0){
				layer.msg("操作进行中，请稍后...",{icon:2});
				return;
			}
			//将标记设置为不可请求
			ajaxStatus = 0;

			$.ajax({
				type:"POST",
				url:context_path + "/inventoryReview/toExamineSolo.do?qaCode=" + qaCode + "&ebsCode=" + ebs_code,
				dataType:"json",
				success:function(data){
					if(data.result){
						layer.msg(data.msg,{icon:1,time:1200});
					}else{
						layer.alert(data.msg, {icon: 2});
					}
					_grid_detail.trigger("reloadGrid");
					ajaxStatus = 1;
				}
			})
		});
	}

	/*//单个审核库位
	function ykPassSolo(qaCode){
		if(ajaxStatusMoveBtn==0){
			layer.msg("操作进行中，请稍后...",{icon:2});
			return;
		}
		//将标记设置为不可请求
		ajaxStatusMoveBtn = 0;

		layer.confirm("确定变更库位吗？",function(){
			$.ajax({
				type:"POST",
				url:context_path + "/inventoryReview/toMoveShelf.do?qaCode=" + qaCode + "&ebsCode=" + ebs_code,
				dataType:"json",
				success:function(data){
					if(data.result){
						layer.msg(data.msg,{icon:1,time:1200});
						_grid_detail.trigger("reloadGrid");
					}else{
						layer.alert(data.msg, {icon: 2});
					}
					ajaxStatusMoveBtn = 1;
				}
			})
		});
	}*/

	//审核日期确认
	$("#inventoryReview_edit_timeConfirm").click(function(){
		layer.confirm("确定将此日期设为审核日期吗？",function(){
			$.ajax({
				type:"POST",
				url:context_path + "/inventoryReview/confirmAuditDate.do?date=" + $("#inventoryReview_edit_time").val() + "&ebsCode=" + ebs_code,
				dataType:"json",
				success:function(data){
					if(data.result){
						layer.msg(data.msg,{icon:1,time:1200});
						_grid_detail.trigger("reloadGrid");
					}else{
						layer.alert("系统错误", {icon: 2});
					}
				}
			})
		});
	});

    //审核按钮AOE：将所有已经盘过的库存上传给ebs，漏盘的不传
	$("#inventoryReview_edit_addMaterialBtn").click(function(){
		if(ajaxStatus==0){
			layer.msg("操作进行中，请稍后...",{icon:2});
			return;
		}

		layer.confirm("确定将所有已经盘点的库存审核通过吗？",function(){
			if(ajaxStatus==0){
				layer.msg("操作进行中，请稍后...",{icon:2});
				return;
			}
			ajaxStatus = 0;    //将标记设置为不可请求

			$.ajax({
				type:"POST",
				url:context_path + "/inventoryReview/toExamineBatch.do?ebsCode=" + ebs_code,
				dataType:"json",
				success:function(data){
					if(data.result){
						layer.closeAll();
						layer.msg(data.msg,{icon:1,time:3000});
						_grid_detail.trigger("reloadGrid");
					}else{
						layer.alert(data.msg, {icon: 2});
					}
					ajaxStatus = 1;
				}
			})
		});
	});

	/*//上传库位按钮AOE
	$("#inventoryReview_edit_allMoveBtn").click(function(){
		if(ajaxStatusMoveBtn==0){
			layer.msg("操作进行中，请稍后...",{icon:2});
			return;
		}
		//将标记设置为不可请求
		ajaxStatusMoveBtn = 0;

		layer.confirm("确定将所有修改库位的库存审核通过吗？",function(){
			$.ajax({
				type:"POST",
				url:context_path + "/inventoryReview/toMoveShelf.do?ebsCode=" + ebs_code,
				dataType:"json",
				success:function(data){
					if(data.result){
						layer.msg(data.msg,{icon:1,time:1200});
						_grid_detail.trigger("reloadGrid");
					}else{
						layer.alert(data.msg, {icon: 2});
					}
					ajaxStatusMoveBtn = 1;
				}
			})
		});
	});*/

	//查询按钮点击事件
	function queryByParam() {
		/*iTsai.form.deserialize($("#inventoryReview_list_hiddenQueryForm"), iTsai.form.serialize($("#inventoryReview_list_queryForm")));
		var queryParam = iTsai.form.serialize($("#inventoryReview_list_hiddenQueryForm"));
		var queryJsonString = JSON.stringify(queryParam);*/
		$("#inventoryReview_edit_grid-table-c").jqGrid("setGridParam", {
			postData: {
				queryJsonString : $("#qacode").val(),
				inventoryState : $("#inventoryReview_list_inventoryResult").val()
			}
		}).trigger("reloadGrid");
	}


	//重置
	function inventoryReview_edit_reset() {
		$("#inventoryReview_list_inventoryResult").select2("val","");
		$("#qacode").val("");
		$("#inventoryReview_edit_grid-table-c").jqGrid("setGridParam", {
			postData: {
				queryJsonString : "",
				inventoryState : ""
			}
		}).trigger("reloadGrid");
	}

	//数量输入验证
	function numberRegex(value, colname) {
		let regex = /^\d+\.?\d{0,2}$/;
		$("#inventoryReview_edit_grid-table-c").jqGrid("setGridParam", {
			postData: {queryJsonString : $("#qacode").val()}
		}).trigger("reloadGrid");
		if (!regex.test(value)) {
			return [false, ""];
		}else  {
			return [true, ""];
		}
	}

	//盘点结果
	$("#inventoryReview_list_inventoryResult").select2({
		placeholder: "选择厂区",
		minimumInputLength:0,   //至少输入n个字符，才去加载数据
		allowClear: true,  //是否允许用户清除文本信息
		delay: 250,
		formatNoMatches:"没有结果",
		formatSearching:"搜索中...",
		formatAjaxError:"加载出错啦！",
		ajax : {
			url: context_path+"/BaseDicType/getKindList",
			type:"POST",
			dataType : 'json',
			delay : 250,
			data: function (term,pageNo) {     //在查询时向服务器端传输的数据
				term = $.trim(term);
				return {
					queryString: term,    //联动查询的字符
					pageSize: 15,    //一次性加载的数据条数
					pageNo:pageNo,    //页码
					description:"INVENTORY_STATE"
				}
			},
			results: function (data,pageNo) {
				var res = data.result;
				if(res.length>0){   //如果没有查询到数据，将会返回空串
					var more = (pageNo*15)<data.total; //用来判断是否还有更多数据可以加载
					return {
						results:res,more:more
					};
				}else{
					return {
						results:{}
					};
				}
			},
			cache : true
		}
	});
</script>